package com.ruoyi.web.controller.app.pay.util;

import com.ruoyi.web.controller.app.pay.wechat.entity.PayInfo;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.*;

/**
 * 文 件 名 :   weixin
 * 描    述 :   微信支付通用工具类
 * 版    本 ：   1.0
 */
public class PayUtil {


   /**
    * 统一下单接口
    */
    public static final String prepayUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    public PayUtil(){}




    public  static TreeMap<String,String>  sortMap(Map<String, String> map){
    	TreeMap<String,String> sort= new TreeMap<>();
         if (map!=null){
             map.forEach((k,v)->{
                 sort.put(k,v);
             });
         }
         return  sort;

    }

    /**
     *  微信H5支付签名算法生成PaySign
     * @param parms
     * @param key
     * @return
     */
    private  static  int  i;
    public static synchronized String  getPaySign(Map<String, String> parms,String key) throws UnsupportedEncodingException{
          if (parms==null){
              return null;
          }
          i = 0;
          StringBuffer sb = new StringBuffer(100);
          parms.forEach((k,v)->{
               if(!StringUtils.isEmpty(v)){
                   if (i==0){
                       sb.append(k+"="+v);
                   }else {
                       sb.append("&"+k+"="+v);
                   }
                   i++;
               }

          });
        sb.append("&key="+key);
        String paySign = Mds5.Get32(sb.toString()).toUpperCase();
        return paySign;

    }
    
    
    /**
     * 
     * @方法说明： 将map转换成xml
     * @param map
     * @return
     */
    
    public static String   ConvertedMapToXml(Map<String, String> map) {
    	//Assert.isNull(map);
    	Document doc = DocumentHelper.createDocument();
    	Element xml = doc.addElement("xml");
    	map.forEach((k,v)->{
    	    if(!StringUtils.isEmpty(v)){
    	    	Element p = 	xml.addElement(k);
        		p.setText(v);
    	    }
    	});
    	return doc.asXML();
		
	}
    
    
    
    public static String getPayParam(Map<String, String> parms){
        if (parms==null){
            return null;
        }
        i = 0;
        StringBuffer sb = new StringBuffer(100);
        parms.forEach((k,v)->{
             if(!StringUtils.isEmpty(v)){
                 if (i==0){
                     sb.append(k+"="+v);
                 }else {
                     sb.append("&"+k+"="+v);
                 }
                 i++;
             }

        });
      return sb.toString();

  }
    
    
    /**
     * 
     * @方法说明： 生成随机数
     * @return
     */
    public static String create_nonce_str() {
    	return UUID.randomUUID().toString().replace("-","");
    	
    }
    
    
    
    /**
     * 
     * 
     * 扩展xstream使其支持CDATA
     * 
     */
    private static XStream xstream = new XStream(new XppDriver() {
	     public HierarchicalStreamWriter createWriter(Writer out) {
		     return new PrettyPrintWriter(out) {
		      //增加CDATA标记
		      boolean cdata = true;
		      @SuppressWarnings("rawtypes")
		      public void startNode(String name, Class clazz) {
		      super.startNode(name, clazz);
		      }
		      protected void writeText(QuickWriter writer, String text) {
		      if (cdata) {
		       writer.write("<![CDATA[");
		       writer.write(text);
		       writer.write("]]>");
		      } else {
		       writer.write(text);
		      }
		      }
		     };
	     }
    });
    
    
    
    
    
    /**
     * 
     * @方法说明：  转化成xml
     * @param pi
     * @return
     */
    public static String payInfoToXML(PayInfo pi) {
    	xstream.alias("xml", pi.getClass());
     return xstream.toXML(pi);
    }
    
    /**
     * 
     * @方法说明： Xml 转化Map
     * @param xml
     * @return
     * @throws Exception
     */
    public static Map<String, String> parseXml(String xml) throws Exception {
    	 Map<String, String> map = new HashMap<String, String>();
    	 Document document = DocumentHelper.parseText(xml);
    	 Element root = document.getRootElement();
    	 List<Element> elementList = root.elements();
    	 for (Element e : elementList)
    	 map.put(e.getName(), e.getText());
    	 return map;
    }
    

   
    /**
     * 建立请求，以表单HTML形式构造，带文件上传功能
     * @param sParaTemp 请求参数数组
     * @param strMethod 提交方式。两个值可选：post、get
     * @param strButtonName 确认按钮显示文字
     * @param strParaFileName 文件上传的参数名
     * @param url    URL支付网关
     * @return 提交表单HTML文本
     */
    public static String buildRequest(Map<String, String> sParaTemp, String strMethod, String strButtonName,String url) {
      
        List<String> keys = new ArrayList<String>(sParaTemp.keySet());

        //待请求参数数组
        Map<String, String> sPara = sParaTemp;

        StringBuffer sbHtml = new StringBuffer();

        sbHtml.append("<form id=\"alipaysubmit\" name=\"alipaysubmit\" action=\"" + url
                      + "_input_charset=utf-8\" method=\"" + strMethod
                      + "\">");

        for (int i = 0; i < keys.size(); i++) {
            String name = (String) keys.get(i);
            String value = (String) sPara.get(name);

            sbHtml.append("<input type=\"hidden\" name=\"" + name + "\" value=\"" + value + "\"/>");
        }

        //submit按钮控件请不要含有name属性
        sbHtml.append("<input type=\"submit\" value=\"" + strButtonName + "\" style=\"display:none;\"></form>");
        sbHtml.append("<script>document.forms['alipaysubmit'].submit();</script>");

        return sbHtml.toString();
        
        
        
        
    }
    
    /**
     * 
     * 方法名：createLinkString
     * 功能描述:创建签名字符串
     *
     * @param params
     * @return
     *
     *
     */
    public static String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }
    
    
/*    public static void main(String[] args) {
		
    	Map<String, String> map = new HashMap<String, String>();
    	map.put("pay_date", "20170322");
    	map.put("batch_no", "2017032210000001");
    	map.put("_input_charset", "utf-8");
    	map.put("notify_url", "http://app.yeneiren.cn:8080/pay/refund/notifyUrl");
    	map.put("batch_fee" , "1");
    	map.put("batch_num", "1");
    	map.put("partner", "2088621208495775");
    	map.put("service", "batch_trans_notify");
    	map.put("account_name", "重庆水纹科技有限公司");
    	map.put("email", "shuiwen_keji@sina.com");
    	map.put("detail_data", "2016644^13883101184^周超^1^付款");
    
    	String str =  PayUtil.createLinkString(map);
    	
    	String mysign   =	MD5.sign(str, "xd9wa6vxd8avhg2oblq4a605h2bmbo7u", "utf-8");
    	System.out.println(mysign);
	}*/
    
   





}
